package com.wj.dubbo.service.welfareshop.service.impl;

import java.io.IOException;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.wj.console.bean.welfareshop.param.ProductQuery;
import com.wj.console.bean.welfareshop.result.Address;
import com.wj.console.bean.welfareshop.result.AfterSaleDetail;
import com.wj.console.bean.welfareshop.result.Cate;
import com.wj.console.bean.welfareshop.result.OrderDetail;
import com.wj.console.bean.welfareshop.result.ProductDetail;
import com.wj.console.common.Page;
import com.wj.console.common.exception.BusinessException;
import com.wj.console.constant.Enums.CACHE_KEY;
import com.wj.console.constant.Enums.SYS_AFTER_SALE_STATUS;
import com.wj.console.constant.Enums.SYS_ORDER_STATUS;
import com.wj.console.constant.Enums.YZH_AFTER_SALE_STATUS;
import com.wj.console.constant.Enums.YZH_ORDER_STATUS;
import com.wj.dubbo.service.cache.MyRedisCache;
import com.wj.dubbo.service.cache.MyRedisCacheManager;
import com.wj.dubbo.service.welfareshop.entity.Product;
import com.wj.dubbo.service.welfareshop.entity.WsAftersale;
import com.wj.dubbo.service.welfareshop.entity.WsAftersaleDetail;
import com.wj.dubbo.service.welfareshop.entity.WsMemberAccount;
import com.wj.dubbo.service.welfareshop.entity.WsMemberPaymentDetails;
import com.wj.dubbo.service.welfareshop.entity.WsSysOrder;
import com.wj.dubbo.service.welfareshop.entity.WsYzhOrder;
import com.wj.dubbo.service.welfareshop.entity.WsYzhOrderDetail;
import com.wj.dubbo.service.welfareshop.service.IWsAftersaleDetailService;
import com.wj.dubbo.service.welfareshop.service.IWsAftersaleService;
import com.wj.dubbo.service.welfareshop.service.IWsMemberAccountService;
import com.wj.dubbo.service.welfareshop.service.IWsMemberPaymentDetailsService;
import com.wj.dubbo.service.welfareshop.service.IWsSysOrderService;
import com.wj.dubbo.service.welfareshop.service.IWsYzhOrderDetailService;
import com.wj.dubbo.service.welfareshop.service.IWsYzhOrderService;
import com.wj.dubbo.utils.PageUtils;
import com.wj.dubbo.utils.UUIDUtils;
import com.wj.dubbo.utils.WsAmountDesUtil;

/**   
 * 类名称：WelfareShopBasicMsgService
 * 类描述 ：福利商城基础信息服务类
 * 创建人: Administrator  
 * 创建时间：2017-5-23 下午1:00:32  
 * 修改人：
 * 修改时间：
 * 修改备注：
 * 版本： V1.0
 */
@Service
public class WelfareShopBasicMsgService {
	private static final Logger log = LoggerFactory.getLogger(WelfareShopBasicMsgService.class);
	@Autowired
	private WelfareShopCallService welfareShopCallService;
	@Autowired
    private MyRedisCacheManager manager;
	@Autowired
	private ProductServiceImpl productServiceImpl;
	@Autowired
	private IWsYzhOrderService wsYzhOrderService;
	@Autowired
	private IWsYzhOrderDetailService wsYzhOrderDetailService;
	@Autowired
	private IWsAftersaleService wsAftersaleService;
	@Autowired
	private IWsAftersaleDetailService wsAftersaleDetailService;
	@Autowired
	private IWsSysOrderService wsSysOrderService;
	@Autowired
	private IWsMemberAccountService wsMemberAccountService;
	@Autowired
	private IWsMemberPaymentDetailsService wsMemberPaymentDetailsService;
	@Autowired
    private RedisTemplate redisTemplate;
	
	public static final String  ADDRESS = "welfareshop-batch:";
	
	/**
	 * 获取所有地址(存入redis)
	 */
	public void putAllAddress(){
		boolean isSuccess = true ;
		try {
			boolean flag = this.redisLock(CACHE_KEY.WS_BATCH_LOCK_ADDRESS.toString(),"address",60*60*6);
			if(flag){
				Long start = System.currentTimeMillis();
				this.welfareShopCallService.getAllAddress();
				this.writeDoneTime("address"); 
				log.info("福利商城获取所有地址成功!耗时："+(System.currentTimeMillis()-start)/1000/60+"分钟");
			}
		} catch (BusinessException e) {
			isSuccess = false;
			log.error("福利商城【获取所有地址】",e.getCode()+":"+e.getMessage());
		} catch (Exception e) {
			isSuccess = false;
			log.error("福利商城【获取所有地址】", e);
		}finally{
			this.redisUnLock(CACHE_KEY.WS_BATCH_LOCK_ADDRESS.toString());
		}
		//地址跑批情况提醒(短信)
		/*if (isSuccess) {
			System.out.println("获取所有地址成功");
		}else{
			System.out.println("获取所有地址失败");
		}*/
	}
	
	private void writeDoneTime(String type) {
		redisTemplate.getConnectionFactory().getConnection().set(("welfare-batch-time:"+type).getBytes(),
				new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()).getBytes());
	}

	private void redisUnLock(String key) {
		redisTemplate.delete(key);
	}

	private boolean redisLock(String key,String value,int time) {
		RedisConnection redisConnect =  redisTemplate.getConnectionFactory().getConnection();
		boolean result = false;
		try {
			boolean flag = this.redisSetnx(redisConnect,key, value);
			if (flag) {
				redisConnect.expire(key.getBytes(),time);
				result = true;
			}
		} finally {
			redisConnect.close();
		}
		return result;
	}

	private boolean redisSetnx(RedisConnection connection,String key, String value) {
		byte[] rediskey = redisTemplate.getKeySerializer().serialize(key);
		byte[] redisvalue = redisTemplate.getValueSerializer().serialize(value); 
		return connection.setNX(rediskey, redisvalue);
	}

	/**
	 * 获取所有商品分类(存入redis)
	 */
	public void putAllCate(){
		boolean isSuccess = true ;
		try {
			boolean flag = this.redisLock(CACHE_KEY.WS_BATCH_LOCK_PRODUCTCATE.toString(),"productCate",60*60*1);
			if(flag){
				Long start = System.currentTimeMillis();
				this.welfareShopCallService.getAllCate();
				this.writeDoneTime("cate");
				log.info("福利商城获取所有商品分类成功!耗时："+(System.currentTimeMillis()-start)/1000+"秒");
			}
		} catch (BusinessException e) {
			isSuccess = false;
			log.error("福利商城【获取所有商品分类】",e.getCode()+":"+e.getMessage());
		} catch (Exception e) {
			isSuccess = false;
			log.error("福利商城【获取所有商品分类】", e);
		}finally{
			this.redisUnLock(CACHE_KEY.WS_BATCH_LOCK_PRODUCTCATE.toString());
		}
		//商品分类跑批情况提醒(短信)
		/*if (isSuccess) {
			System.out.println("获取所有分类成功");
		}else{
			System.out.println("获取所有分类失败");
		}*/
	}
	
	/**
	 * 获取所有商品信息(存入redis、索引)
	 */
	public void putAllProduct(){
		boolean isSuccess = true ;
		try {
			boolean flag = this.redisLock(CACHE_KEY.WS_BATCH_LOCK_PRODUCT.toString(),"product",60*60*1);
			if(flag){
				Long start = System.currentTimeMillis();
				Map<String,ProductDetail> productMap= this.welfareShopCallService.getAllProducts();
				//索引
				Product product = null;
				List<Product> products = new ArrayList<Product>();
				for(String key:productMap.keySet()){
					product = new Product();
					BeanUtils.copyProperties(productMap.get(key), product);
					product.setId(product.getProductId());
					products.add(product);
				}
				
				List<Product> oldProducts = productServiceImpl.findAllProduct();
				List<Product> needDeleteList = new ArrayList<Product>();
				
				if(oldProducts==null||oldProducts.size()==0){
					//第一次添加商品
					productServiceImpl.save(products);
				}else{
					for(Product oldProduct:oldProducts){
						if(productMap.get(oldProduct.getProductId().toString())==null){
							needDeleteList.add(oldProduct);
						}
					}
					//删除不存在商品
					productServiceImpl.delete(needDeleteList);
					//添加/更新商品
					productServiceImpl.save(products);
				}
				//放入缓存
				MyRedisCache  cache = (MyRedisCache)manager.getCache(CACHE_KEY.WS_PRODUCT.toString());
				cache.put(CACHE_KEY.WS_PRODUCT_MAP.toString(), productMap);
				this.writeDoneTime("product");
				log.info("福利商城获取所有商品信息成功!耗时："+(System.currentTimeMillis()-start)/1000+"秒");
			}
			
		} catch (BusinessException e) {
			isSuccess = false;
			log.error("福利商城【获取所有商品信息】",e.getCode()+":"+e.getMessage());
		} catch (Exception e) {
			isSuccess = false;
			log.error("福利商城【获取所有商品信息】", e);
		}finally{
			this.redisUnLock(CACHE_KEY.WS_BATCH_LOCK_PRODUCT.toString());
		}
		//商品分类跑批情况提醒(短信)
		/*if (isSuccess) {
			System.out.println("获取所有商品成功");
		}else{
			System.out.println("获取所有商品失败");
		}*/
	}
	
	/**
	 * 更新商品信息
	 * @param products
	 */
	public void updateProduct(List<ProductDetail> productDetails) {
		MyRedisCache  cache = (MyRedisCache)manager.getCache(CACHE_KEY.WS_PRODUCT.toString());
		Map<String,ProductDetail> productMap  = (Map<String,ProductDetail>) cache.get(CACHE_KEY.WS_PRODUCT_MAP.toString(),Map.class);
		
		Product product = null;
		List<Product> products = new ArrayList<Product>();
		
		for(ProductDetail detail:productDetails){
			product = new Product();
			BeanUtils.copyProperties(detail, product);
    		product.setId(product.getProductId());
    		products.add(product);
    		productMap.put(detail.getProductId().toString(), detail);
    	}
		//更新索引
		productServiceImpl.save(products);
		//更新缓存
		cache.put(CACHE_KEY.WS_PRODUCT_MAP.toString(), productMap);
	}

	/**
	 * 获取单个商品详情(缓存获取)
	 * @param pid 商品ID
	 */
	public ProductDetail getProductDetailFromCach(String pid) {
		MyRedisCache  cache = (MyRedisCache)manager.getCache(CACHE_KEY.WS_PRODUCT.toString());
		Map<String,ProductDetail> productMap  = (Map<String,ProductDetail>) cache.get(CACHE_KEY.WS_PRODUCT_MAP.toString(),Map.class);
		ProductDetail detail = null;
		if(productMap!=null&&!productMap.isEmpty()){
			detail = productMap.get(pid);
		}
		return detail;
	}

	/**
	 * 获取所有商品
	 */
	public List<ProductDetail> getAllProductsForCache() {
		MyRedisCache  cache = (MyRedisCache)manager.getCache(CACHE_KEY.WS_PRODUCT.toString());
		Map<String,ProductDetail> productMap  = (Map<String,ProductDetail>) cache.get(CACHE_KEY.WS_PRODUCT_MAP.toString(),Map.class);
		List<ProductDetail> productDetails = null;
		if(productMap!=null&&!productMap.isEmpty()){
			 productDetails = new ArrayList<ProductDetail>(productMap.values());
		}
		return productDetails;
	}
	
	/**
	 * 产品分页查询
	 * @param page
	 * @return
	 */
	public Page<ProductQuery, ProductDetail> queryProductsByPage(Page<ProductQuery, ProductDetail> page){
		ProductQuery query = page.getQuery();
		if(null == query){
			return page;
		}
		List<ProductDetail> products = getAllProductsForCache();
		List<ProductDetail> matchedList = new ArrayList<ProductDetail>();
		if (products==null) {
			page.setItemList(matchedList);
			return page;
		}
		for(ProductDetail product : products){
			//满足条件
			if(filter(product, query)){
				matchedList.add(product);
			}
		}
		if(matchedList.isEmpty()){
			page.setItemList(matchedList);
			return page;
		}
		
		//排序
		sortByCondition(matchedList,query);
		
		page.setTotalNum(matchedList.size());
		page.setItemList(PageUtils.pageList(matchedList, page.getPageSize(), page.getCurrentPage()));
		return page;
	}
	
	private void sortByCondition(List<ProductDetail> matchedList, ProductQuery query) {
		if (StringUtils.isEmpty(query.getSortCreateTime())&&StringUtils.isEmpty(query.getSortRetailPrice())) {
			//时间倒序
			Collections.sort(matchedList, new Comparator<ProductDetail>() {
				@Override
				public int compare(ProductDetail o1, ProductDetail o2) {
					return o2.getCreateTime().compareTo(o1.getCreateTime());
				}
			});
		}else{
			if (StringUtils.equals(query.getSortCreateTime(), "1")){
				//时间升序
				Collections.sort(matchedList, new Comparator<ProductDetail>() {
					@Override
					public int compare(ProductDetail o1, ProductDetail o2) {
						return o1.getCreateTime().compareTo(o2.getCreateTime());
					}
				});
			}else if (StringUtils.equals(query.getSortCreateTime(), "2")) {
				//时间倒序
				Collections.sort(matchedList, new Comparator<ProductDetail>() {
					@Override
					public int compare(ProductDetail o1, ProductDetail o2) {
						return o2.getCreateTime().compareTo(o1.getCreateTime());
					}
				});
			}
			
			if (StringUtils.equals(query.getSortRetailPrice(), "1")){
				//价格升序
				Collections.sort(matchedList, new Comparator<ProductDetail>() {
					@Override
					public int compare(ProductDetail o1, ProductDetail o2) {
						return o1.getRetailPrice().compareTo(o2.getRetailPrice());
					}
				});
			}else if (StringUtils.equals(query.getSortRetailPrice(), "2")) {
				//价格降序
				Collections.sort(matchedList, new Comparator<ProductDetail>() {
					@Override
					public int compare(ProductDetail o1, ProductDetail o2) {
						return o2.getRetailPrice().compareTo(o1.getRetailPrice());
					}
				});
			}
			
		}
	}
	

	/**
	 * 过滤符合产品是否符合条件
	 * @param target
	 * @param query
	 * @return
	 */
	private boolean filter(ProductDetail target, ProductQuery query){
		boolean matched = true;
		//产品ID查询
		if(query.getProductId() != null){
			matched = matched && target.getProductId().equals(query.getProductId());
		}
		//产品名称模糊匹配
		if(!StringUtils.isEmpty(query.getName())){
			matched = matched && StringUtils.containsIgnoreCase(target.getName(), query.getName()); 
		}
		//一级产品分类
		if(!StringUtils.isEmpty(query.getRootCate())){
			matched = matched && StringUtils.equals(target.getRootCate(), query.getRootCate());
		}
		//二级产品分类
		if(!StringUtils.isEmpty(query.getTwoCate())){
			matched = matched && StringUtils.equals(target.getTwoCate(), query.getTwoCate());
		}
		//三级产品分类
		if(!StringUtils.isEmpty(query.getThreeCate())){
			matched = matched && StringUtils.equals(target.getThreeCate(), query.getThreeCate());
		}
		
		if(!StringUtils.isEmpty(query.getStatus())){
			matched = matched && StringUtils.equals(target.getStatus(), query.getStatus());
		}
		
		//查询字段产品ID或产品名称
		if(!StringUtils.isEmpty(query.getKeyword())){
			matched = matched && (StringUtils.containsIgnoreCase(target.getName(), query.getKeyword()) 
					               || StringUtils.equals(String.valueOf(target.getProductId()), query.getKeyword())
					               );
		}
		
		return matched;
	}
	
	
	
	/**
	 * 获取单个地址详情
	 * @return RpcResponse data 地址信息
	 * @param code 地址code
	 */
	public Address getAddress(String code) {
		MyRedisCache  cache = (MyRedisCache)manager.getCache(CACHE_KEY.WS_ADDRESS.toString());
		Map<String,Address> addressMap  = (Map<String,Address>) cache.get(CACHE_KEY.WS_ADDRESS_MAP_TILE.toString(),Map.class);
		Address address = null;
		if(addressMap!=null&&!addressMap.isEmpty()){
			address = addressMap.get(code);
		}
		
		if(address != null){
			Address tmpAddr = new Address();
			BeanUtils.copyProperties(address, tmpAddr, "addressMap");
			return tmpAddr;
		}
		return null;
	}
	
	/**
	 * 获取地址
	 * @param province 省
	 * @param city 市
	 * @param county 县/区
	 */
	public List<Address> getAddress(String province, String city, String county) {
		MyRedisCache  cache = (MyRedisCache)manager.getCache(CACHE_KEY.WS_ADDRESS.toString());
		Map<String,Address> addressMap  = (Map<String,Address>) cache.get(CACHE_KEY.WS_ADDRESS_MAP_TREE.toString(),Map.class);
		Map<String,Address> resultMap = null;
		List<Address> addressList = null;
		if(addressMap!=null&&!addressMap.isEmpty()){
			//获取省份
			if(StringUtils.isEmpty(province)){
				resultMap = addressMap;
			}else {
				//获取省下面的市
				if(StringUtils.isEmpty(city)){
					Address provinceAddress = addressMap.get(province);
					if(provinceAddress!=null){
						resultMap = provinceAddress.getAddressMap();
					}
				}else{
					//获取市下面的县/区
					if(StringUtils.isEmpty(county)){
						Address provinceAddress = addressMap.get(province);
						if(provinceAddress!=null){
							Map<String,Address> cityMap = provinceAddress.getAddressMap();
							if(cityMap!=null){
								Address cityAddress = cityMap.get(city);
								if(cityAddress!=null){
									resultMap = cityAddress.getAddressMap();
								}
							}
						}
					}else{
						//获取区/县 下面的 镇/街道
						Address provinceAddress = addressMap.get(province);
						if(provinceAddress!=null){
							Map<String,Address> cityMap = provinceAddress.getAddressMap();
							if(cityMap!=null){
								Address cityAddress = cityMap.get(city);
								if(cityAddress!=null){
									Map<String,Address> countyMap = cityAddress.getAddressMap();
									if(countyMap!=null){
										Address countyAddress = countyMap.get(county);
										if(countyAddress!=null){
											resultMap = countyAddress.getAddressMap();
										}
									}
								}
							}
						}
					}
				}
			}
			if(resultMap!=null&&!resultMap.isEmpty()){
				addressList = new ArrayList<Address>(resultMap.values());
			}
		}
		List<Address> tmpList = null;
		//返回的应该是地址副本
		if(addressList != null){
			tmpList = new ArrayList<Address>(addressList.size());
			for(Address addr : addressList){
				Address tmpAddr = new Address();
				BeanUtils.copyProperties(addr, tmpAddr, "addressMap");
				tmpList.add(tmpAddr);
			}
		}
		return tmpList;
	}
	
	/**
	 * 获取单个分类详情
	 * @param code 地址code
	 */
	public Cate getCate(String code) {
		MyRedisCache  cache = (MyRedisCache)manager.getCache(CACHE_KEY.WS_CATE.toString());
		Map<String,Cate> cateMap  = (Map<String,Cate>) cache.get(CACHE_KEY.WS_CATE_MAP_TILE.toString(),Map.class);
		Cate cate = null;
		if(cateMap!=null&&!cateMap.isEmpty()){
			cate = cateMap.get(code);
		}
		
		if(cate != null){
			Cate tmpCate = new Cate();
			BeanUtils.copyProperties(cate, tmpCate, "cateMap");
			return tmpCate;
		}
		return null;
	}
	
	
	/**
	 * 获取分类详情列表
	 * @param codeList 地址code列表
	 */
	public List<Cate> queryCateList(List<String> codeList) {
		MyRedisCache  cache = (MyRedisCache)manager.getCache(CACHE_KEY.WS_CATE.toString());
		Map<String,Cate> cateMap  = (Map<String,Cate>) cache.get(CACHE_KEY.WS_CATE_MAP_TILE.toString(),Map.class);
		List<Cate> resultList = new ArrayList<Cate>();
		Cate tmpCate = null;
		if(cateMap!=null&&!cateMap.isEmpty()){
			for(String code : codeList){
				tmpCate = cateMap.get(code);
				if(null != tmpCate){
					resultList.add(tmpCate);
				}
			}
		}
		return resultList;
	}
	
	/**
	 * 获取商品分类
	 * @param rootCate 一级分类
	 * @param twoCate 二级分类
	 * @return RpcResponse data 商品分类
	 * 
	 */
	public List<Cate> getCates(String root, String two) {
		MyRedisCache  cache = (MyRedisCache)manager.getCache(CACHE_KEY.WS_CATE.toString());
		Map<String,Cate> cateMap  = (Map<String,Cate>) cache.get(CACHE_KEY.WS_CATE_MAP_TREE.toString(),Map.class);
		Map<String,Cate> resultMap = null;
		List<Cate> cateList = null;
		if(cateMap!=null&&!cateMap.isEmpty()){
			//获取一级分类
			if(StringUtils.isEmpty(root)){
				resultMap = cateMap;
			}else {
				//获取二级分类
				if(StringUtils.isEmpty(two)){
					Cate rootCate = cateMap.get(root);
					if(rootCate!=null){
						resultMap = rootCate.getCateMap();
					}
				}else{
					//获取三级分类
					Cate rootCate = cateMap.get(root);
					if(rootCate!=null){
						Map<String,Cate> twoMap = rootCate.getCateMap();
						if(twoMap!=null){
							Cate twoCate = twoMap.get(two);
							if(twoCate!=null){
								resultMap = twoCate.getCateMap();
							}
						}
					}
				}
			}
			if(resultMap!=null&&!resultMap.isEmpty()){
				cateList = new ArrayList<Cate>(resultMap.values());
			}
		}
		List<Cate> tmpList = null;
		if(cateList != null){
			tmpList = new ArrayList<Cate>(cateList.size());
			for(Cate cate : cateList){
				Cate tmpCate = new Cate();
				BeanUtils.copyProperties(cate, tmpCate, "cateMap");
				tmpList.add(tmpCate);
			}
		}
		return tmpList;
	}
	
	/**
	 * 订单与售后单状态跑批
	 * @throws Exception 
	 * @throws IOException 
	 */
	public void orderStatusBatch(){
		try{
			boolean flag = this.redisLock(CACHE_KEY.WS_BATCH_LOCK_ORDERSTATUS.toString(),"orderStatus",60*60*1);
			if(flag){
				//获取所有状态为 【待发货、待收货、售后中】订单并跑批
				Wrapper<WsYzhOrder> orderQueryWrapper = new EntityWrapper<WsYzhOrder>();
				orderQueryWrapper.in("my_status",SYS_ORDER_STATUS.WAIT_SEND.toString()+","
						+SYS_ORDER_STATUS.WAIT_RECEIVE.toString() +","+SYS_ORDER_STATUS.AFTER_SALEING.toString());
				int count = this.wsYzhOrderService.selectCount(orderQueryWrapper);
				if(count!=0){
					List<WsYzhOrder> yzhOrderList = this.wsYzhOrderService.selectList(orderQueryWrapper);
					//变量声明
					String orderNo = null;	//云中鹤订单编号
					OrderDetail orderDetail = null; //云中鹤返回订单详情
					String orderStatusNow = null;//云中鹤当前订单状态
					
					WsAftersale wsAftersale = null;
					AfterSaleDetail afterSaleDetail = null; //云中鹤返回售后单详情
					String afterSaleStatusNow = null;//云中鹤当前售后状态
					
					WsSysOrder wsSysOrder = null;	//系统订单
					WsMemberAccount wsMemberAccount = null; //员工积分账户
					
					for(WsYzhOrder yzhOrder:yzhOrderList){
						try{
							orderNo = yzhOrder.getOrderNo();
							//云中鹤实时订单状态查询
							try {
								orderDetail = welfareShopCallService.orderDetail(orderNo);
								orderStatusNow = orderDetail.getStatus();
							} catch (BusinessException e) {
								log.error("福利商城接口调用【查询订单详情】", e.getCode()+":"+e.getMessage());
							} catch (Exception e) {
								log.error("福利商城接口调用【查询订单详情】", e);
							}
							if(orderStatusNow!=null){
								switch (SYS_ORDER_STATUS.get(yzhOrder.getMyStatus())) {
								//待发货、待收货
								case WAIT_SEND:
								case WAIT_RECEIVE:
									//等待确认收货
									if(YZH_ORDER_STATUS.WAITING_CONFIRMED.eq(orderStatusNow)){
										yzhOrder.setYzhStatus(YZH_ORDER_STATUS.WAITING_CONFIRMED.toString());
										yzhOrder.setMyStatus(SYS_ORDER_STATUS.WAIT_RECEIVE.toString());	//待收货
									//订单已完成
									}else if(YZH_ORDER_STATUS.COMPLETED.eq(orderStatusNow)){
										yzhOrder.setYzhStatus(YZH_ORDER_STATUS.COMPLETED.toString());
										yzhOrder.setMyStatus(SYS_ORDER_STATUS.ALREADY_COMPLETE.toString());	//已完成
									}
									yzhOrder.setUpdateTime(new Date());
									this.wsYzhOrderService.updateById(yzhOrder);
									break;
								//售后中
								case AFTER_SALEING:
									yzhOrder.setYzhStatus(orderStatusNow);
									//查找订单下面状态为【待确认、售后中】的售后单
									Wrapper<WsAftersale> afterSaleQueryWrapper = new EntityWrapper<WsAftersale>();
									afterSaleQueryWrapper.eq("yzh_order_no", orderNo);
									afterSaleQueryWrapper.in("sys_status", SYS_AFTER_SALE_STATUS.WAIT_SURE.toString()
											+ ","+ SYS_AFTER_SALE_STATUS.AFTER_SALEING.toString());
									count = this.wsAftersaleService.selectCount(afterSaleQueryWrapper);
									//同一订单下处于 【待确认、售后中】的 售后单 只可能有一个
									if(count==1){
										wsAftersale = this.wsAftersaleService.selectOne(afterSaleQueryWrapper);
										//云中鹤实时售后单状态查询
										try {
											afterSaleDetail = welfareShopCallService.afterSaleDetail(orderNo);
											afterSaleStatusNow = afterSaleDetail.getStatus();
										} catch (BusinessException e) {
											log.error("福利商城接口调用【查询售后订单详情】", e.getCode()+":"+e.getMessage());
										} catch (Exception e) {
											log.error("福利商城接口调用【查询售后订单详情】", e);
										}
										if(afterSaleStatusNow!=null){
											switch (YZH_AFTER_SALE_STATUS.get(afterSaleStatusNow)) {
											case WAIT_RECEIVE: //等待仓库收货
												wsAftersale.setYzhStatus(YZH_AFTER_SALE_STATUS.WAIT_RECEIVE.toString());
												wsAftersale.setSysStatus(SYS_AFTER_SALE_STATUS.AFTER_SALEING.toString());//售后中
												break;
											case REFUND_PROCESSING: //退款处理中
												wsAftersale.setYzhStatus(YZH_AFTER_SALE_STATUS.REFUND_PROCESSING.toString());
												wsAftersale.setSysStatus(SYS_AFTER_SALE_STATUS.AFTER_SALEING.toString());//售后中
												break;
											case ALREADY_COMPLETE: //已完成
												wsAftersale.setYzhStatus(YZH_AFTER_SALE_STATUS.ALREADY_COMPLETE.toString());
												wsAftersale.setSysStatus(SYS_AFTER_SALE_STATUS.ALREADY_COMPLETE.toString());//已完成
												
												if("1".equals(wsAftersale.getType())){//退货
													//退积分额度
													Wrapper<WsSysOrder> sysOrderQueryWrapper = new EntityWrapper<WsSysOrder>();
													sysOrderQueryWrapper.eq("order_no", yzhOrder.getSysOrderNo());
													wsSysOrder = this.wsSysOrderService.selectOne(sysOrderQueryWrapper);
													wsMemberAccount = this.wsMemberAccountService.selectByForUpdate(wsSysOrder.getAccountId());
													BigDecimal balanceAmt = new BigDecimal(WsAmountDesUtil.decrypt(wsMemberAccount.getBalance()));
													//本售后单下商品总和
													
													List<WsAftersaleDetail> afterSaleDetails = this.wsAftersaleDetailService.queryByAftersaleId(wsAftersale.getId());
													BigDecimal returnAmt = new BigDecimal(0);
													if(afterSaleDetails!=null && afterSaleDetails.size()>0){
														for(WsAftersaleDetail detail:afterSaleDetails){
															returnAmt = returnAmt.add(detail.getProductPrice().multiply(new BigDecimal(detail.getProductNum())));
														}
													}
													balanceAmt = balanceAmt.add(returnAmt); 
													wsMemberAccount.setBalance(WsAmountDesUtil.encrypt(balanceAmt.toString()));
													
													//更改订单状态(myStatus)
													this.disposeMyStatus(yzhOrder,wsAftersale);
													this.wsMemberAccountService.updateById(wsMemberAccount);
													
													//积分收入记录
													WsMemberPaymentDetails detail = new WsMemberPaymentDetails();
													detail.setId(UUIDUtils.getUUIDStr());
													detail.setMemberId(wsMemberAccount.getMemberId());
													detail.setAmount(returnAmt);
													detail.setTp("1"); //收入
													detail.setBusTp("3"); //退款
													detail.setDes("退款");
													detail.setCreateTime(new Date());
													this.wsMemberPaymentDetailsService.insert(detail);
												}else if("2".equals(wsAftersale.getType())){//换货
													yzhOrder.setMyStatus(SYS_ORDER_STATUS.ALREADY_COMPLETE.toString());//已完成
												}
												break;
											case ALREADY_REFUSE: //已拒绝
												wsAftersale.setYzhStatus(YZH_AFTER_SALE_STATUS.ALREADY_REFUSE.toString());
												wsAftersale.setSysStatus(SYS_AFTER_SALE_STATUS.ALREADY_REFUSE.toString());//已驳回
												yzhOrder.setMyStatus(SYS_ORDER_STATUS.ALREADY_COMPLETE.toString());//已完成
												break;
											default:
												break;
											}
											yzhOrder.setUpdateTime(new Date());
											wsAftersale.setUpdateTime(new Date());
											this.wsAftersaleService.updateById(wsAftersale);
											this.wsYzhOrderService.updateById(yzhOrder);
										}
									}
									break;
								default:
									break;
								}
							}
						 }catch(Exception e){
							  log.error("订单/售后单状态跑批："+e);
						 }	
					}
				}
			}
		}catch(Exception e){
			log.error("订单/售后单状态跑批："+e);
		}finally{
			this.redisUnLock(CACHE_KEY.WS_BATCH_LOCK_ORDERSTATUS.toString());
		}	
	}
	
	/**
	 * 
	 * @param yzhOrder 云中鹤订单
	 * @param wsAftersale 当前售后单
	 */
	private void disposeMyStatus(WsYzhOrder yzhOrder, WsAftersale wsAftersale) {
		//当前售后单下商品明细
		List<WsAftersaleDetail> afterSaleDetails = this.wsAftersaleDetailService.queryByAftersaleId(wsAftersale.getId());
		//订单中已经退货完成的商品明细(商品ID,商品数量)
		Map<String,Integer> productMap = new HashMap<String,Integer>();
		this.calculateProductNum(productMap,afterSaleDetails);
		
		//当前订单下所有退货已完成售后单
		Wrapper<WsAftersale> aftersaleQueryWrapper = new EntityWrapper<WsAftersale>();
		aftersaleQueryWrapper.eq("yzh_order_no", yzhOrder.getOrderNo());
		aftersaleQueryWrapper.eq("type","1"); //退货
		aftersaleQueryWrapper.eq("sys_status", SYS_AFTER_SALE_STATUS.ALREADY_COMPLETE.toString());//已完成
		List<WsAftersale> afterSales = this.wsAftersaleService.selectList(aftersaleQueryWrapper);
		//将退款已完成售后单下商品数量都总结到Map中
		if(afterSales!=null&&afterSales.size()>0){
			for(WsAftersale afterSale:afterSales){
				afterSaleDetails = this.wsAftersaleDetailService.queryByAftersaleId(afterSale.getId());
				this.calculateProductNum(productMap,afterSaleDetails);
			}
		}
		//map中商品数量与订单下商品作对比
		boolean isEquals = true;//售后退货已完成商品与订单下商品一致
		Integer productNum = null;
		Wrapper<WsYzhOrderDetail> orderDetailQueryWrapper = new EntityWrapper<WsYzhOrderDetail>();
		orderDetailQueryWrapper.eq("order_no", yzhOrder.getOrderNo());
		List<WsYzhOrderDetail> orderDetails = this.wsYzhOrderDetailService.selectList(orderDetailQueryWrapper);
		for(WsYzhOrderDetail orderDetail:orderDetails){
			productNum = productMap.get(orderDetail.getProductId());
			if(productNum==null||orderDetail.getProductNum()!=productNum){
				isEquals = false;
				break;
			}
		}
		if(isEquals){
			yzhOrder.setMyStatus(SYS_ORDER_STATUS.ALREADY_REFUND.toString());//已退款
		}else{
			yzhOrder.setMyStatus(SYS_ORDER_STATUS.PART_REFUND.toString());//部分退款
		}
	}
	
	private void calculateProductNum(Map<String, Integer> productMap,
			List<WsAftersaleDetail> afterSaleDetails) {
		for(WsAftersaleDetail detail:afterSaleDetails){
			if(productMap.get(detail.getProductId())==null){
				productMap.put(detail.getProductId(), detail.getProductNum());
			}else{
				Integer productNum = productMap.get(detail.getProductId());
				productNum = productNum+detail.getProductNum();
				productMap.put(detail.getProductId(),productNum);
			}
		}
	}

}
